package com.peternguyen.totolistpro;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import com.peternguyen.totolistpro.dao.CategoryDAO;
import com.peternguyen.totolistpro.dao.TodoDAO;
import com.peternguyen.totolistpro.data.Category;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter {
	private Activity activity;
	private ArrayList<Category> data;
	private static LayoutInflater inflater = null;
	public ImageLoader imageLoader;
	CategoryDAO dao;
	TodoDAO tdDao;
	Context ct;

	public LazyAdapter(Activity a, ArrayList<Category> d) {
		activity = a;
		data = d;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(activity.getApplicationContext());
		dao = new CategoryDAO(a);
		tdDao = new TodoDAO(a);
		ct = activity.getApplicationContext();
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View vi = convertView;
		if (convertView == null)
			vi = inflater.inflate(R.layout.list_row, null);

		TextView title = (TextView) vi.findViewById(R.id.title_todo); // title
		TextView artist = (TextView) vi.findViewById(R.id.lblTodo); // artist
		// name
		// TextView duration = (TextView) vi.findViewById(R.id.duration); //
		// duration
		ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image); // thumb
																				// image

		Category cat = new Category();
		cat = data.get(position);

		// Setting all values in listview
		title.setText(cat.get_name());
		artist.setText(String.valueOf(tdDao.countTodo(cat.get_id())) + " "
				+ ct.getString(R.string.num_todo));
		if (cat.get_img() != null) {
			byte[] outImage = cat.get_img();
			ByteArrayInputStream imageStream = new ByteArrayInputStream(
					outImage);
			Bitmap theImage = BitmapFactory.decodeStream(imageStream);
			thumb_image.setImageBitmap(theImage);
		} else {

		}
		// duration.setText(song.get(CategoryActivity.KEY_DURATION));
		// thumb_image.setImageBitmap(song.get(CategoryActivity.THUMB_URL));

		/*
		 * ImageButton btn = (ImageButton) vi.findViewById(R.id.btndelete);
		 * btn.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub
		 * 
		 * //onListItemClick(this, this, position, data.get(position), v); }
		 * 
		 * });
		 */

		return vi;
	}

}